package com.hualan.sfzyproject.controller;

import com.hualan.sfzyproject.domain.Users;
import com.hualan.sfzyproject.mapper.UsersMapper;
import com.hualan.sfzyproject.service.UserService;
import com.hualan.sfzyproject.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UsersMapper usersMapper;

    //登录
    @GetMapping("/login")
    public R userLogin(String username,String password){
        int i = userService.userLogin(username,password);
        Map<String, Object> userMap = new HashMap<>();

        if (i == 1){//登陆成功
            userMap.put("token",UUID.randomUUID());
            Users users = usersMapper.selectByUsername(username);
            userMap.put("user",users);
            return R.ok(userMap); //把对象传上去
        }else if (i == -1){
            return R.error("密码错误");
        }else{
            return R.error("用户名/手机号不存在");
        }
    }

    //注册
    @PostMapping("register")
    public R register(@RequestBody Users user) throws ClassNotFoundException, SQLException {

        int i = userService.register(user);
        if (i > 0) {
            //获取注册对象
            Users inneruser = usersMapper.selectByUsername(user.getUserName());
            Integer id = inneruser.getUserId();
            return R.ok(id);
        } else {
            return R.fail("注册失败");
        }
    }

    //修改
    @PutMapping
    public R updateUser(@RequestBody Users user){

        int i = userService.updateUser(user);
        if (i > 0) {
            return R.success("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }



}
